package com.example.qiushibaike.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.example.qiushibaike.adapter.JokeAdapter;
import com.example.qiushibaike.model.JokeModel;
import com.example.qiushibaike.Utils.NetUtils;
import com.example.qiushibaike.R;

import java.io.IOException;
import java.util.concurrent.Executors;


/**
 * 趣图界面
 */
public class FunnyImageFragment extends android.support.v4.app.Fragment {

    public static final String JOKEURL = "http://v.juhe.cn/joke/randJoke.php?key=ae240f7fba620fc370b803566654949e&type=pic";
    private JokeModel mJokeModel = new JokeModel();
    private RecyclerView mRecyclerView;
    private JokeAdapter mAdapter;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Executors.newSingleThreadExecutor().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String result = NetUtils.getData(JOKEURL);
                    mJokeModel = JSON.parseObject(result, JokeModel.class);
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            LinearLayoutManager layoutmanager = new LinearLayoutManager(getActivity());
                            //设置RecyclerView 布局
                            mRecyclerView.setLayoutManager(layoutmanager);

                            mAdapter = new JokeAdapter(mJokeModel.result);
                            mRecyclerView.setAdapter(mAdapter);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_joke, null);
        mRecyclerView = view.findViewById(R.id.recycleview);
        return view;
    }
}
